﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using log4net;
using System.Xml.Serialization;
using System.Collections;
using System.Xml;
using Softyum.Common.utils;
using Softyum.Common.xml;
using System.Drawing;
using System.Xml.Linq;

namespace Softyum.ForexAgent.Config
{
    /// <summary>
    /// 应用程序配置文件的缓存对象
    /// </summary>
    public class ConfigManager
    {
        public class ShortcutClass
        {
            public string Activate { get; set; }
        }

        #region Logging
        private static readonly ILog log = LogManager.GetLogger(typeof(ConfigManager));
        #endregion

        public PopupWindowSettings PopupWindowSettings { get; private set; }

        private const string CONFIG_FILE_NAME = "ForexAgent.xml";
        private String ConfigFilePath { get; set; }

        public ShortcutClass Shortcut { get; private set; }

        private Hashtable cacheTable = new Hashtable();

        public ConfigManager()
        {
            //
            PopupWindowSettings = new Config.PopupWindowSettings();
            // Set config file path
            ConfigFilePath = AppDirectory + CONFIG_FILE_NAME;
            //
            Shortcut = new ShortcutClass();
        }

        public void Reload()
        {
            XElement doc = XElement.Load(ConfigFilePath);
            // initialize popup window
            PopupWindowSettings.Reload();
            
            // Shortcut
            var shortcuts = from item in doc.Element("Shortcuts").Descendants("Shortcut")
                            select item;
            foreach (var sc in shortcuts)
            {
                if (sc.Attribute("name").Value == "activate")
                {
                    Shortcut.Activate = sc.Attribute("key").Value;
                }
            }
         
        }

        public void Save()
        {
            // PopupWindow
            ColorConverter colorConverter = new ColorConverter();
            FontConverter fontConverter = new FontConverter();
            XElement doc = XElement.Load(ConfigFilePath);
            XElement e = null;
             
            //
            PopupWindowSettings.Save();
            // Shortcut
            e = (from el in doc.Element("Shortcuts").Elements("Shortcut")
                where el.Attribute("name").Value == "activate"
                select el).First();
            e.SetAttributeValue("activate", Shortcut.Activate);

            // Save
            doc.Save(ConfigFilePath);
        }

        public string AppDirectory
        {
            get { return AppDomain.CurrentDomain.BaseDirectory; }
        }

    }
}
